using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using TerritoryGame.Application.Dtos;
using TerritoryGame.Application.Interfaces;
using TerritoryGame.Application.Commands;
using TerritoryGame.Domain.Interfaces;
using TerritoryGame.Domain.DomainEvents;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;

namespace TerritoryGame.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly IAppAuthService _authServices;
    private readonly IAppTokenService _tokenService;
    private readonly IDomainEventPublisher _eventPublisher;

    public AuthController(
        IAppAuthService authServices, 
        IAppTokenService tokenService,
        IDomainEventPublisher eventPublisher)
    {
        _authServices = authServices;
        _tokenService = tokenService;
        _eventPublisher = eventPublisher;
    }

    /// <summary>
    /// 用户注册
    /// </summary>
    [HttpPost("register")]
    [AllowAnonymous] // 注册不需要Token验证
    public async Task<IActionResult> Register([FromBody] UserRegisterDto dto)
    {
        var res = await _authServices.RegisterAsync(dto);
        return Ok(res);
    }

    /// <summary>
    /// 用户登录
    /// </summary>
    [HttpPost("login")]
    [AllowAnonymous]
    public async Task<IActionResult> Login([FromBody] UserLoginDto dto)
    {
        try
        {
            // 输入验证
            if (dto == null)
            {
                return BadRequest(new { 
                    code = 400, 
                    message = "请求数据不能为空", 
                    data = (object?)null,
                    timestamp = DateTime.UtcNow
                });
            }

            if (string.IsNullOrWhiteSpace(dto.Username))
            {
                return BadRequest(new { 
                    code = 400, 
                    message = "用户名不能为空", 
                    data = (object?)null,
                    timestamp = DateTime.UtcNow
                });
            }

            if (string.IsNullOrWhiteSpace(dto.Password))
            {
                return BadRequest(new { 
                    code = 400, 
                    message = "密码不能为空", 
                    data = (object?)null,
                    timestamp = DateTime.UtcNow
                });
            }

            // 调用服务层登录
            var result = await _authServices.LoginAsync(dto);
            
            if (result.Code == 200)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { 
                code = 500, 
                message = $"登录时发生内部错误: {ex.Message}", 
                data = (object?)null,
                timestamp = DateTime.UtcNow
            });
        }
    }

    /// <summary>
    /// 刷新访问令牌
    /// </summary>
    [HttpPost("refresh-token")]
    [AllowAnonymous]
    public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenDto dto)
    {
        try
        {
            // 输入验证
            if (dto == null)
            {
                return BadRequest(new { 
                    code = 400, 
                    message = "请求数据不能为空", 
                    data = (object?)null,
                    timestamp = DateTime.UtcNow
                });
            }

            if (string.IsNullOrWhiteSpace(dto.RefreshToken))
            {
                return BadRequest(new { 
                    code = 400, 
                    message = "刷新令牌不能为空", 
                    data = (object?)null,
                    timestamp = DateTime.UtcNow
                });
            }

            // 验证刷新令牌格式
            if (!dto.RefreshToken.StartsWith("eyJ"))
            {
                return BadRequest(new { 
                    code = 400, 
                    message = "刷新令牌格式错误，不是有效的JWT格式", 
                    data = (object?)null,
                    timestamp = DateTime.UtcNow
                });
            }

            // 调用服务层刷新令牌
            var result = await _authServices.SmartRefreshTokenAsync(dto.RefreshToken, dto.ForceRefresh);
            
            if (result.Code == 200)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { 
                code = 500, 
                message = $"刷新令牌时发生内部错误: {ex.Message}", 
                data = (object?)null,
                timestamp = DateTime.UtcNow
            });
        }
    }

    /// <summary>
    /// 验证用户信息（忘记密码前验证）
    /// </summary>
    [HttpPost("validate-user-info")]
    [AllowAnonymous]
    public async Task<IActionResult> ValidateUserInfo([FromBody] ValidateUserInfoDto dto)
    {
        try
        {
            // 输入验证
            if (string.IsNullOrWhiteSpace(dto.Email))
            {
                return BadRequest(new { 
                    code = 400, 
                    message = "邮箱不能为空", 
                    data = (object?)null,
                    timestamp = DateTime.UtcNow
                });
            }

            if (string.IsNullOrWhiteSpace(dto.Phone))
            {
                return BadRequest(new { 
                    code = 400, 
                    message = "手机号不能为空", 
                    data = (object?)null,
                    timestamp = DateTime.UtcNow
                });
            }

            var result = await _authServices.ValidateUserInfoAsync(dto);
            return Ok(result);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { 
                code = 500, 
                message = $"验证用户信息时发生错误: {ex.Message}", 
                data = (object?)null,
                timestamp = DateTime.UtcNow
            });
        }
    }



    /// <summary>
    /// 忘记密码
    /// </summary>
    [HttpPost("forget-password")]
    [AllowAnonymous] // 忘记密码不需要Token验证
    public async Task<IActionResult> ForgetPassword([FromBody] ForgetPasswordDto dto)
    {
        var res = await _authServices.ForgetPasswordAsync(dto);
        return Ok(res);
    }



    /// <summary>
    /// 获取当前用户ID
    /// </summary>
    private Guid GetCurrentUserId()
    {
        // 尝试从多种claim类型中获取用户ID
        var userIdClaim = User.FindFirst("sub")?.Value
            ?? User.FindFirst("user_id")?.Value
            ?? User.FindFirst("uid")?.Value
            ?? User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
            
        if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
        {
            return Guid.Empty;
        }
        return userId;
    }
}

